package com.awanp3.nimbus.system.dubbo;

import cn.hutool.json.JSONUtil;
import com.awanp3.nimbus.common.core.exception.ServiceException;
import com.awanp3.nimbus.common.core.utils.*;
import com.awanp3.nimbus.system.api.RemoteTokenService;
import com.awanp3.nimbus.system.api.domain.vo.RemoteLoginVo;
import com.awanp3.nimbus.system.domain.vo.*;
import com.awanp3.nimbus.system.form.HWorkLoginBody;
import com.awanp3.nimbus.system.strategy.IAuthStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

/**
 * token 控制
 *
 * @author 20014170
 */
@Slf4j
@RequiredArgsConstructor
@Service
@DubboService
public class RemoteTokenServiceImpl implements RemoteTokenService {

    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    @Override
    public RemoteLoginVo login(String body) {
        HWorkLoginBody loginBody = JSONUtil.toBean(body, HWorkLoginBody.class);
        ValidatorUtils.validate(loginBody);

        String grantType = loginBody.getGrantType();
        if (!"hWork".equals(grantType)) {
            throw new ServiceException("只允许H-Work Token方式远程登录。");
        }

        // 登录
        LoginVo loginVo = IAuthStrategy.login(body, grantType);

        return MapstructUtils.convert(loginVo, RemoteLoginVo.class);
    }

}
